import csv

import requests
from lxml import etree

list = []


class Guanzi(object):
    def __init__(self):
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36"
        }
        cookies = 'antipas=9iJX88768563sC79575J4S97H353; uuid=33540ac3-bc97-4eb0-cb81-0dce6f290b78; clueSourceCode=%2A%2300; Hm_lvt_bf3ee5b290ce731c7a4ce7a617256354=1605140021; ganji_uuid=1823228510099384685932; sessionid=aa03e774-c6bb-4fd0-8e67-2eadcb900d94; lg=1; cainfo=%7B%22ca_a%22%3A%22-%22%2C%22ca_b%22%3A%22-%22%2C%22ca_s%22%3A%22self%22%2C%22ca_n%22%3A%22self%22%2C%22ca_medium%22%3A%22-%22%2C%22ca_term%22%3A%22-%22%2C%22ca_content%22%3A%22-%22%2C%22ca_campaign%22%3A%22-%22%2C%22ca_kw%22%3A%22-%22%2C%22ca_i%22%3A%22-%22%2C%22scode%22%3A%22-%22%2C%22keyword%22%3A%22-%22%2C%22ca_keywordid%22%3A%22-%22%2C%22display_finance_flag%22%3A%22-%22%2C%22platform%22%3A%221%22%2C%22version%22%3A1%2C%22client_ab%22%3A%22-%22%2C%22guid%22%3A%2233540ac3-bc97-4eb0-cb81-0dce6f290b78%22%2C%22ca_city%22%3A%22suqian%22%2C%22sessionid%22%3A%22aa03e774-c6bb-4fd0-8e67-2eadcb900d94%22%7D; cityDomain=bj; user_city_id=12; preTime=%7B%22last%22%3A1605140396%2C%22this%22%3A1605140020%2C%22pre%22%3A1605140020%7D; Hm_lpvt_bf3ee5b290ce731c7a4ce7a617256354=1605140396'

        self.cookies_dict = {temp[:temp.find("=")]: temp[temp.find("=") + 1:] for temp in cookies.split("; ")}

    def main(self, url):
        self.r = requests.post(url=url, headers=self.headers, cookies=self.cookies_dict)

        self.html = etree.HTML(self.r.text)
        # print(r.text)
        info_list = self.html.xpath('//ul/li/a[@target="_blank"]')
        # print("提取到的个数：", len(info_list))
        for info in info_list:
            item = {}
            item['title'] = info.xpath('./h2/text()')[0]
            item['时间'] = info.xpath('./div[@class="t-i"]/text()')[0]
            item['路程'] = info.xpath('./div[@class="t-i"]/text()')[1]
            price = info.xpath('./div[@class="t-price"]/p/text()')[0]
            price_str = str(price) + '万'
            item['现价'] = price_str
            item['原价'] = info.xpath('./div[@class="t-price"]/em/text()')[0]
            list.append(item)
            # print(item)



    def write(self):
        with open('./二手车信息.csv', 'w+', encoding='utf-8') as f:
            f_csv = csv.DictWriter(f, ['title', '时间', '路程', '现价', '原价'])
            f_csv.writeheader()
            f_csv.writerows(list)


if __name__ == '__main__':
    gz = Guanzi()
    for i in range(10):
        url = 'https://www.guazi.com/bj/buy/o%s' % (i)
        gz.main(url)
        print('正在打印第%s页'% (i+1))
    gz.write()
